﻿using Lg.Core.Form.Types;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Lg.Core.Form
{
    public class TypeFactory
    {
        public static  IType? GetType(string? className)
        {
            if (className == null)
            {
                throw new ArgumentNullException("TypeFactory Error:类名不可为空!");
            }
            return ReflectionHelper.CreateInstance<IType>($"Lg.Core.Form.Types.{className}", "Lg.Core");
        }

        public static IType? GetType(string? className,string? jsonData)
        {
            if (className != null && jsonData != null)
            {
                Type? type = Type.GetType($"Lg.Core.Form.Types.{className},Lg.Core");
                MethodInfo methodInfo = typeof(TypeFactory).GetMethod("ToModel")!;
                MethodInfo obj = methodInfo.MakeGenericMethod(type!);
                IType? model= (IType?)obj.Invoke(new TypeFactory(), new string[] { jsonData });
                if (model != null)
                {
                    return model;
                }
                else
                {
                    throw new Exception($"对像:{className}反序列化失败！");
                }
            }
            else
            {
                throw new Exception($"参数不可为空！");
            }
            
        }
        /// <summary>
        /// 将JSON格式的字符串反序列化为实体model
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="str">JSON格式字符串</param>
        /// <returns>Model</returns>
        public static IType ToModel<T>(string data) where T : IType
        {
            try
            {
                return JsonConvert.DeserializeObject<T>(data)!;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
    }
}
